package com.nnnu.wsnackshop.listener;

import cn.hutool.core.lang.UUID;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.nnnu.wsnackshop.pojo.dto.ProductExcelModel;
import com.nnnu.wsnackshop.utils.AliOssUtil;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
public class ProductImportListener extends AnalysisEventListener<ProductExcelModel> {
    private final Map<Integer, byte[]> pictureMap;
    private final AliOssUtil ossUtil;

    @Getter
    private List<ProductExcelModel> list = new ArrayList<>();

    public ProductImportListener(AliOssUtil ossUtil, Map<Integer, byte[]> pictureMap) {
        this.ossUtil = ossUtil;
        this.pictureMap = pictureMap;
    }

    @Override
    public void invoke(ProductExcelModel data, @NotNull AnalysisContext context) {
        int excelRowNum = context.readRowHolder().getRowIndex();

        // 跳过标题行（根据实际设置）
        if (excelRowNum == 0) return;

        // 使用Excel物理行号获取图片
        byte[] img = pictureMap.get(excelRowNum);

        // 添加行号打印
        System.out.println("处理行: " + excelRowNum + ", 图片存在: " + (img != null));

        if (img != null) {
            String objectName = "products/" + UUID.randomUUID() + ".jpg";
            String url = ossUtil.upload(img, objectName);
            data.setImageUrl(url);
            System.out.println("行" + excelRowNum + "图片上传成功: " + url);
        } else {
            // 打印可用行号以便调试
            String availableRows = pictureMap.keySet().stream()
                    .map(String::valueOf)
                    .collect(Collectors.joining(", "));
            log.warn("行 {} 缺少图片 - 可用行号: {}", excelRowNum, availableRows);
        }
        list.add(data);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("所有行分析完毕，已处理图片 {} 張", list.size());
    }
}

